package com.easylinkin.linkappapi.safe.util;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import sun.misc.BASE64Encoder;

/**
 * @Author: kan yuanfeng
 * @Date: 2022/9/13 11:58
 * @Description:
 */
public class ImageUtil {

  /**
   * 将本地图片转换成Base64编码字符串
   *
   * @param imgFile 图片目录路径
   * @return
   */
  public static String getImgFileToBase64(String imgFile) {
    /**
     * 将网络图片转换成Base64编码字符串
     *
     * @param imgUrl 网络图片Url
     * @return
     */
      InputStream inputStream = null;
      ByteArrayOutputStream outputStream = null;
      byte[] buffer = null;
      try {
        // 创建URL
        URL url = new URL(imgFile);
        // 创建链接
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setConnectTimeout(5000);
        inputStream = conn.getInputStream();
        outputStream = new ByteArrayOutputStream();
        // 将内容读取内存中
        buffer = new byte[1024];
        int len = -1;
        while ((len = inputStream.read(buffer)) != -1) {
          outputStream.write(buffer, 0, len);
        }
        buffer = outputStream.toByteArray();
      } catch (IOException e) {
        e.printStackTrace();
      } finally {
        if (inputStream != null) {
          try {
            // 关闭inputStream流
            inputStream.close();
          } catch (IOException e) {
            e.printStackTrace();
          }
        }
        if (outputStream != null) {
          try {
            // 关闭outputStream流
            outputStream.close();
          } catch (IOException e) {
            e.printStackTrace();
          }
        }
      }
      // 对字节数组Base64编码
      return new BASE64Encoder().encode(buffer);
    }

  public static byte[] image2byte(String path) throws IOException {
    byte[] data = null;
    URL url = null;
    InputStream input = null;
    try{
      url = new URL(path);
      HttpURLConnection httpUrl = (HttpURLConnection) url.openConnection();
      httpUrl.connect();
      httpUrl.getInputStream();
      input = httpUrl.getInputStream();
    }catch (Exception e) {
      e.printStackTrace();
      return null;
    }
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    byte[] buf = new byte[1024];
    int numBytesRead = 0;
    while ((numBytesRead = input.read(buf)) != -1) {
      output.write(buf, 0, numBytesRead);
    }
    data = output.toByteArray();
    output.close();
    input.close();
    return data;
  }
}
